<?php
/**
 * （Logic）解析移库报告(已停用)
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Amazon\FbaRemovalShipment;
use App\Util\RExcel;
class ParseRemovalShipmentReport
{
    /**
     * 解析RemovalShipment
     * @param $file
     * @param $account
     * @return int
     */
    public static function exeParse($file,$account){
        $lines = RExcel::importFile($file);
        $i = 0;
        $count = 0;
        $head = [];
        foreach($lines as $_str){
            $str = ParseReport::getReplaceStr($_str);
            if($i == 0){
                $head = ParseReport::getTableHeadKey($str,self::$_keys);
                if(empty($head))return 2;
            }else{
                $flag = self::_addRemovalShipment($account->id,$head,$str);
                $flag && $count++;
            }
            $i++;
        }
        return $i==($count+1) ? 2 : 3;
    }

    private static $_keys = ['request-date',
                             'order-id',
                             'shipment-date',
                             'sku',
                             'fnsku',
                             'shipped-quantity',
                             'carrier',
                             'tracking-number'];
    /**
     * 添加RemovalShipment
     * @param $accountId
     * @param $head
     * @param $str
     * @return bool
     */
    private static function _addRemovalShipment($accountId,$head,$str){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keys;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        $requestDate = date('Y-m-d H:i:s',strtotime($temp[$head['request-date']]) - date("Z"));
        $shipmentDate = date('Y-m-d H:i:s',strtotime($temp[$head['shipment-date']]) - date("Z"));
        $count = FbaRemovalShipment::query()
            ->where('account_id',$accountId)
            ->where('order_id',$temp[$head['order-id']])
            ->where('shipment_date',$shipmentDate)
            ->where('sku',$temp[$head['sku']])
            ->where('shipped_quantity',$temp[$head['shipped-quantity']])
            ->count();
        if($count > 0)return true;
        $re = FbaRemovalShipment::query()->create([
            'account_id' => $accountId,
            'request_date' => $requestDate,
            'order_id' => $temp[$head['order-id']],
            'shipment_date' => $shipmentDate,
            'sku' => $temp[$head['sku']],
            'fnsku' => $temp[$head['fnsku']],
            'shipped_quantity' => $temp[$head['shipped-quantity']],
            'carrier' => $temp[$head['carrier']],
            'tracking_number' => $temp[$head['tracking-number']],
        ]);
        return !$re ? false : true;
    }
}
